﻿using UnityEngine;
using UnityEngine.UI;
using NetFrame;
using LitJson;
using UniRx;

public class NetFrameworkDemo : MonoBehaviour
{
    private long uid = -1;
    private bool isConnect = false;
    public Button ConnectButton;
    public Button LoginButton;
    public Button EntryGameButton;
    public Button DataTestButton;

    void Start()
    {
        //添加Http数据返回的响应事件
        HttpConnect.GetInstance().HttpRespEvent += HttpCallBack;
        //添加主服务器socket数据返回的响应事件
        ProtoManager.Instance.AddRespDelegate(NetProtocols.ENTRY_GAME, MainServerCallBack);
        ProtoManager.Instance.AddRespDelegate(NetProtocols.TESTA, MainServerCallBack);

        ConnectButton = transform.Find("ConnectButton").GetComponent<Button>();
        LoginButton = transform.Find("LoginButton").GetComponent<Button>();
        EntryGameButton = transform.Find("EntryGame").GetComponent<Button>();
        DataTestButton = transform.Find("DataTest").GetComponent<Button>();

        ConnectButton.OnClickAsObservable().Subscribe(_ => OnConnectServerClick()).AddTo(this);
        LoginButton.OnClickAsObservable().Subscribe(_ => DeviceLogin()).AddTo(this);
        EntryGameButton.OnClickAsObservable().Subscribe(_ => EntryGame()).AddTo(this);
        DataTestButton.OnClickAsObservable().Subscribe(_ => DataTest()).AddTo(this);
    }

    void OnDistance()
    {
        HttpConnect.GetInstance().HttpRespEvent -= HttpCallBack;
        ProtoManager.Instance.DelRespDelegate(NetProtocols.ENTRY_GAME, MainServerCallBack);
        ProtoManager.Instance.DelRespDelegate(NetProtocols.TESTA, MainServerCallBack);
    }

    /// <summary>
    /// 与服务器建立连接按键
    /// </summary>
    public void OnConnectServerClick()
    {
        SocketHelper.GetInstance().Connect(ConnectConfig.main_server_ip, ConnectConfig.main_server_port, ConnectSuccessed, ConnectFailed);
    }

    /// <summary>
    /// 注册连接按键
    /// </summary>
    public void OnEntryGameClick()
    {
        if (!isConnect)
        {
            Debug.Log("请先连接服务器！");
        }
        else if (uid == -1)
        {
            Debug.Log("请先进行登录！");
        }
        else
        {
            EntryGame();
        }
    }

    /// <summary>
    /// 使用设备码进行游客登录
    /// </summary>
    public void DeviceLogin()
    {
        //Dictionary<string, string> post = new Dictionary<string, string>();
        string device = SystemInfo.deviceUniqueIdentifier;
        //post.Add("device", device);
        WWWForm post = new WWWForm();
        post.AddField("logic", HttpProtocols.DEVICELOGIN);
        post.AddField("device", device);
        HttpConnect.GetInstance().SendHttpResquest(post, true);
    }

    /// <summary>
    /// 响应Http返回
    /// </summary>
    /// <param name="httpProtocol">请求类型</param>
    /// <param name="httpData">数据</param>
    /// <param name="hrs">状态</param>
    public void HttpCallBack(HttpResponse resp)
    {
        if (resp.GetStatus() == HttpReturnStatus.Successed)
        {
            switch (resp.GetHttpProtocol())
            {
                case HttpProtocols.DEVICELOGIN:
                    Debug.Log("游客登录返回的数据(json):" + resp.GetData());

                    JsonData jd = JsonMapper.ToObject(resp.GetData());
                    uid = long.Parse(jd["uid"].ToJson());
                    break;
            }
        }
        else
        {
            Debug.Log("Http错误提示：" + resp.GetErrorString());
        }

    }

    /// <summary>
    /// 主服务器回调
    /// </summary>
    /// <param name="r"></param>
    public void MainServerCallBack(Resp r)
    {
        switch (r.GetProtocol())
        {
            case NetProtocols.ENTRY_GAME:
                Debug.Log("进入游戏");
                break;
            case NetProtocols.TESTA:
                TestAResp resp = (TestAResp)r;
                Debug.Log(resp.testInt);
                Debug.Log(resp.testLong);
                Debug.Log(resp.testString);
                Debug.Log(resp.cont);
                break;
        }
    }

    /// <summary>
    /// 进入游戏，进入游戏后才可以进行数据的上传或下载
    /// </summary>
    public void EntryGame()
    {
        EntryGameReq req = new EntryGameReq(uid);
        req.Send();
    }

    /// <summary>
    /// 连接服务器成功
    /// </summary>
    public void ConnectSuccessed()
    {
        isConnect = true;
        Debug.Log("连接服务器成功！");
    }

    /// <summary>
    /// 连接服务器失败
    /// </summary>
    public void ConnectFailed()
    {
        Debug.Log("连接服务器失败！");
    }

    /// <summary>
    /// 数据上传下载的练习
    /// </summary>
    public void DataTest()
    {
        TestAReq req = new TestAReq(1, 1000000000, "测试A");
        req.Send();
    }
}
